package com.education.platform.api.controller.iosPay;

import com.alibaba.fastjson.JSONObject;
import com.education.platform.api.service.PayRecordService;
import com.education.platform.api.service.SysDictionaryService;
import com.education.platform.api.vo.request.IapOrderVerifyRequestVO;
import com.education.platform.api.vo.request.PayRecordUpdateVO;
import com.education.platform.api.vo.response.IosCreateOrderResponseVO;
import com.education.platform.common.enums.DicTypeEnum;
import com.education.platform.common.enums.PaymentTypeEnum;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.util.BeanUtil;
import com.education.platform.common.util.StringUtils;
import com.education.platform.dao.entity.PayRecordDO;
import com.education.platform.dao.entity.SysDictionaryDO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@RestController
@Api("iosPay")
@RequestMapping("iosPay")
@Validated
public class IosPayController {

    private static final Logger log = LoggerFactory.getLogger(IosPayController.class);

    @Autowired
    private PayRecordService payRecordService;
    @Autowired
    private SysDictionaryService sysDictionaryService;


    /**
     * 苹果内购校验
     *
     * @return
     */
    @ApiOperation(value = "内购验证")
    @PostMapping("/verify")
    public Boolean verify(@RequestBody @Valid IapOrderVerifyRequestVO requestVO) {
        log.info("苹果内购校验开始：" + requestVO);
        //线上环境验证
        String verifyResult = IosVerifyUtil.buyAppVerify(requestVO.getReceiptData(), 1);
        if (verifyResult == null) {
            log.error("苹果验证失败，返回数据为空");
            throw new BusinessException("苹果验证失败");
        } else {
            log.info("正式环境-苹果平台返回JSON:" + verifyResult);
            JSONObject appleReturn = JSONObject.parseObject(verifyResult);
            String states = appleReturn.getString("status");
            //无数据则沙箱环境验证
            if ("21007".equals(states)) {
                verifyResult = IosVerifyUtil.buyAppVerify(requestVO.getReceiptData(), 0);
                log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
                appleReturn = JSONObject.parseObject(verifyResult);
                states = appleReturn.getString("status");
            }
            log.info("苹果平台返回值：appleReturn" + appleReturn);
            // 前端所提供的收据是有效的    验证成功
            if ("0".equals(states)) {
                String receipt = appleReturn.getString("receipt");
                JSONObject returnJson = JSONObject.parseObject(receipt);
                String inApp = returnJson.getString("in_app");
                List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
                if (!CollectionUtils.isEmpty(inApps)) {
                    for (HashMap app : inApps) {
                        if (requestVO.getTransactionId().equals(app.get("transaction_id"))) {
                            String productId = (String) app.get("product_id");
                            log.info("productId=" + productId);
                            PayRecordDO recordDO = checkProduct(productId);
                            recordDO.setPaymentPlatformNo(requestVO.getTransactionId());
                            payRecordService.iapPayRecord(recordDO);
                            log.info("购买成功");
                            return Boolean.TRUE;
                        }
                    }
                    throw new BusinessException("当前交易不在交易列表中");
                }
                throw new BusinessException("未能获取获取到交易列表");
            } else {
                throw new BusinessException("支付失败，错误码：" + states);
            }
        }
    }

    /**
     * 验证product
     * @param productId
     * @return
     */
    private PayRecordDO checkProduct(String productId) {
        List<SysDictionaryDO> dics = sysDictionaryService.getListByDicTypeCodeList(Arrays.asList(DicTypeEnum.IAP_TYPE.getValue()));
        for (SysDictionaryDO dic : dics) {
            if (dic.getCode().equals(productId)) {
                PayRecordDO payRecordDO = new PayRecordDO();
                //对应的豆子数
                payRecordDO.setNumber(Integer.valueOf(dic.getName()));
                //支付价格
                payRecordDO.setTotalPrice(this.getMoney(productId));
                return payRecordDO;
            }
        }
        throw new BusinessException("不存在的产品类型！");
    }

    /**
     * 获取价格
     * @param productId
     * @return
     */
    private BigDecimal getMoney(String productId) {
        if (StringUtils.isEmpty(productId)) {
            throw new BusinessException("productId为空");
        }
        String[] str = productId.split("_");
        if (str.length == 2) {
            return new BigDecimal(str[1]);
        }
        throw new BusinessException("productId格式不正确");
    }


    public static void main(String[] args) {

        String parem = "MIITvgYJKoZIhvcNAQcCoIITrzCCE6sCAQExCzAJBgUrDgMCGgUAMIIDXwYJKoZIhvcNAQcBoIIDUASCA0wxggNIMAoCAQgCAQEEAhYAMAoCARQCAQEEAgwAMAsCAQECAQEEAwIBADALAgEDAgEBBAMMATEwCwIBCwIBAQQDAgEAMAsCAQ8CAQEEAwIBADALAgEQAgEBBAMCAQAwCwIBGQIBAQQDAgEDMAwCAQoCAQEEBBYCNCswDAIBDgIBAQQEAgIAnzANAgENAgEBBAUCAwHV7TANAgETAgEBBAUMAzEuMDAOAgEJAgEBBAYCBFAyNTUwGAIBBAIBAgQQ3jD2ViDuBotD7w+XBudQdDAbAgEAAgEBBBMMEVByb2R1Y3Rpb25TYW5kYm94MBwCAQUCAQEEFHMq0woYYyVNCEJ+qXTO2S7a7mY0MB4CAQwCAQEEFhYUMjAyMC0wOS0xNVQxNDowNDo1MFowHgIBEgIBAQQWFhQyMDEzLTA4LTAxVDA3OjAwOjAwWjAgAgECAgEBBBgMFmNvbS55aXl1YW5saXNoaS52dWxjYW4wNAIBBgIBAQQszjfPAqFkY7TJ6aevMdJ7OXxZ6nohfzBTtV8ZdV/f8KhadJB3PpgM4VLboIAwRgIBBwIBAQQ+JhMJ9zkJaDu5n8SBj3DNx7TDlMMaEucXiuSFdIVc0EKAZd1wiv/dJ9JMze9cDF1peOSD2jCkAdWLB7NbOV4wggFfAgERAgEBBIIBVTGCAVEwCwICBqwCAQEEAhYAMAsCAgatAgEBBAIMADALAgIGsAIBAQQCFgAwCwICBrICAQEEAgwAMAsCAgazAgEBBAIMADALAgIGtAIBAQQCDAAwCwICBrUCAQEEAgwAMAsCAga2AgEBBAIMADAMAgIGpQIBAQQDAgEBMAwCAgarAgEBBAMCAQEwDAICBq4CAQEEAwIBADAMAgIGrwIBAQQDAgEAMAwCAgaxAgEBBAMCAQ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F0aW9ucyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eQIIDutXh+eeCY0wCQYFKw4DAhoFADANBgkqhkiG9w0BAQEFAASCAQBVSeO5JWFu67KAtTjV0TgSBBiqRaiBy+ZjcmVJ/urmnL/oqCyEcjlT2eawEca0NNfKZfbgMtxR++qWWkAectrj/xS5+pSAHY0Dx0PWt/CvveeccbNYcRYz7FuyEoyZnbbnuy5kMeWfJR5gMOBjrQPGfehP+Qtzfb/y1zC9qaz3TuCV1S5XmD1DcgNGeGZxJK3AL9hL9VuAJIGQjq4Gx9u7plFQLgeHXS7wEEDDXthw6viNXiAIyd/Y867MmPqp5H1yXSDDZ0/UKSPXNibOSGgm3Af5Q+842Nw19uRXRI9VeRFWF0svTwPY3oqXXLWNHlb1zYeDYkK7SSTuYvI8DaWK";
                String verifyResult = IosVerifyUtil.buyAppVerify(parem, 0);
        log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
//        JSONObject appleReturn = JSONObject.parseObject(verifyResult);
//        String states = appleReturn.getString("status");
    }

}
